package com.nxy.test.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;

/**
 * Created by snailnan on 2017/2/21.
 */
public class NioSocketClient {
	public static void main(String[] args) throws IOException {
		requestMessage();

	}

	public static void requestMessage() throws IOException {
		SocketChannel sc = SocketChannel.open();
		sc.configureBlocking(false);
		sc.connect(new InetSocketAddress("127.0.0.1", 6666));

		while (!sc.finishConnect()) {
		}

		ByteBuffer writeBuf = ByteBuffer.wrap("hello/".getBytes());
		ByteBuffer readBuf = ByteBuffer.allocate(20);
		while (writeBuf.hasRemaining()) {
			sc.write(writeBuf);
		}
		int c = sc.read(readBuf);
		while (c != -1) {
			readBuf.flip();
			while (readBuf.hasRemaining()) {
				System.out.print((char) readBuf.get());
			}
			readBuf.clear();
			c = sc.read(readBuf);
		}
		sc.close();
	}
}
